/*
 * @lc app=leetcode.cn id=278 lang=javascript
 *
 * [278] 第一个错误的版本
 */

// @lc code=start
/**
 * Definition for isBadVersion()
 * 
 * @param {integer} version number
 * @return {boolean} whether the version is bad
 * isBadVersion = function(version) {
 *     ...
 * };
 */

/**
 * @param {function} isBadVersion()
 * @return {function}
 */
var solution = function(isBadVersion) {
    /**
     * @param {integer} n Total versions
     * @return {integer} The first bad version
     */
    return function(n) {
        let range = [1, n]

        let getVersion = (range) => {
            if (range[0] === range[1]) {
                // 如果找到了该版本
                return range[0]
            }
            if (range[0] + 1 === range[1]) {
                if (isBadVersion(range[0])) {
                    return range[0]
                }
                return range[1]
            }

            let temp = Math.floor((range[1] - range[0]) / 2) // 想下取整中间版本
            if (isBadVersion(range[0] + temp)) {
                // 错误仍在前面版本
                range = [range[0], range[0] + temp]
            } else {
                // 错误在后面版本
                range = [range[0] + temp, range[1]]
            }
            return getVersion(range)
        }

        return getVersion(range)
        
    };
};
// @lc code=end

